<?php
use yii\helpers\Url;

$web = Url::base();
$scriptUrl = \Yii::$app->request->scriptUrl;
?>
<style>
    .messageDemo {
        width: 250px;
        height: 400px;
        position: relative;
        z-index: 0
    }

    .messageDemo img {
        position: absolute;
        top: 0;
        left: 0;
        width: 250px;
        height: 400px;
    }

    .messageDemo p {
        position: absolute;
        margin-top: 120px;
        margin-left: 45px;
        width: 170px;
        z-index: 10;
        font-family: "微软雅黑";
        font-size: 12px;
        word-break: break-all;
        background-color: #F7F7F7;

    }
</style>

<script type="application/javascript">

    var sendrecord = {}; //定义发放积分记录内容
    var userList = new Array(); //发放用户列表
    var walfareId = '';
    var insCode = 0;  //操作人员机构
    var insSelect2;  //主页面机构下拉
    var insSelect3;  //导入页面机构下拉
    var insSelectDepartment;  //导入页面子机构下拉
    var department = ''; //操作人员子机构


    $(function ($) {
        loading.hide();
        //操作人员机构
        insCode = "<?= $institution?>";
        department = "<?=$department?>";

        //主页面机构下拉列表内容初始化
        var institution =  <?= json_encode($institutionList) ?>;
        insSelect2 = $('#select2').treeAutocomplete({
            defaultText: '----请选择机构----',
            source: institution,
            onSelected: function (element) {
                //新增子机构选择
                var department_div = $("#department_div");
                var html = "";
                html += '<div id="inputdepartment"></div>';
                department_div.html(html);
                var institution_code = element.getValue();
                var action = "<?=$scriptUrl?>" + "/common" + "/department-tree-handler";
                var data = {};
                data.institution_code = institution_code;
                requestJson(action, data, true, function (responseData) {
                    if (responseData.status == 0 && responseData.data != '') {
                        $('#inputdepartment').treeAutocomplete({
                            defaultText: "--选择子机构(部门)--",
                            isShowCode: false,
                            source: responseData.data
                        });
                        $("#department_div").css("display", "block");
                    } else {
                        $("#department_div").css("display", "none");
                    }
                });

            }
        }).setValue("<?= $selectedInstitution ?>");

        //子机构有缺省值，则初始子机构化树
        if (!("<?= $selectedInstitution ?>" == '' || "<?= $selectedInstitution ?>" == 0) || !(insCode == '' || insCode == '0')) {
            var department_selected = $("#department_div");
            var html_selected = "";
            html_selected += '<div id="inputdepartment"></div>';
            department_selected.html(html_selected);
            var institution_code;
            if (!("<?= $selectedInstitution ?>" == '' || "<?= $selectedInstitution ?>" == 0)) {
                institution_code = "<?=$selectedInstitution?>";
            } else if (!(insCode == '' || insCode == '0')) {
                institution_code = "<?=$institution?>";
            }
            var action = "<?=$scriptUrl?>" + "/common" + "/department-tree-handler";
            var data = {};
            data.institution_code = institution_code;
            requestJson(action, data, true, function (responseData) {
                if (responseData.status == 0 && responseData.data != '') {
                    $('#inputdepartment').treeAutocomplete({
                        defaultText: "--选择子机构(部门)--",
                        isShowCode: false,
                        source: responseData.data
                    }).setValue("<?= $selectedDepartment ?>");
                    $("#department_div").css("display", "block");
                } else {
                    $("#department_div").css("display", "none");
                }
            });

        }


        //导入页面机构下拉列表内容初始化
        insSelect3 = $('#select3').treeAutocomplete({
            defaultText: '----请选择机构----',
            source: institution,
            onSelected: function (element) {
                changeMessageDemo();
                //新增子机构选择
                var department_div = $("#departmentImport_div");
                var html = "";
                html += '<div id="inputdepartment_import"></div>';

                department_div.html(html);

                var institution_code = element.getValue();
                var action = "<?=$scriptUrl?>" + "/common" + "/department-tree-handler";
                var data = {};
                data.institution_code = institution_code;
                requestJson(action, data, true, function (responseData) {
                    if (responseData.status == 0 && responseData.data !='') {
                        $('#inputdepartment_import').treeAutocomplete({
                            defaultText: "--选择子机构(部门)--",
                            isShowCode: false,
                            source: responseData.data
                        });
                        $('#subIns').css('display','block');
                    }else{
                        $('#subIns').css('display','none');
                    }
                });

            }
        }).setValue(insCode);

        //子机构管理员，导入页面，初始化子机构树
        if (!(insCode == '' || insCode == '0')) {
            var department_selected = $("#departmentImport_div");
            var html_selected = "";
            html_selected += '<div id="inputdepartment_import"></div>';
            department_selected.html(html_selected);
            var institution_code = "<?=$institution?>";
            var action = "<?=$scriptUrl?>" + "/common" + "/department-tree-handler";
            var data = {};
            data.institution_code = institution_code;
            requestJson(action, data, true, function (responseData) {
                if(responseData.status == 0 && responseData.data !=''){
                $('#inputdepartment_import').treeAutocomplete({
                    defaultText: "--选择子机构(部门)--",
                    isShowCode: false,
                    source: responseData.data
                }).setValue("<?= $department ?>");
                $('#subIns').css('display','block');
                }else{
                    $('#subIns').css('display','none');
                }
            });
        }


        if ("<?= $filter ?>" == 0) {
            $('#search1').val("");
        } else {
            $('#search1').val("<?= $filter ?>");
        }

        if ("<?= $startTime ?>" == 0) {
            $('#startTime').val("");
        } else {
            $('#startTime').val("<?= $startTime ?>");
        }

        if ("<?= $endTime ?>" == 0) {
            $('#endTime').val("");
        } else {
            $('#endTime').val("<?= $endTime ?>");
        }

        $('#detailWalfare').on('show.bs.modal', function (e) {
            $("#detail_content").html('正在加载数据....');
            var data = {};
            data.id = e.relatedTarget.attributes['data-walfare-id'].value;
            requestHtml('walfare-summary-partview', data, true, function (responseHtml) {
                $("#detail_content").html(responseHtml);
            });
        });
        /* if (insCode != '0') {
         $("#select2").attr("disabled", true);
         }*/
    });

    //发积分
    function addWalfare(institutionId) {
        $("#addWalfare").modal('show');
        $("#step1").show();
        $("#step2").hide();
        $("#step3").hide();
        //机构列表内容确认
        $("#reason").val('');
        $("#walfareType").val(1);
        $(".two-error").text('');
        $("#alert1").css("display", "none");
        $("#alert3").css("display", "none");
        $("#alert4").css("display", "none");
        $("#importlist").css("display", "none");
        $("#importlist").contents().find("tbody").html("");
        $("#preStep").attr("disabled", false);
        changeMessageDemo();
        //alert($("#importlist").contents().find("tbody").html());
    }

    //第一步onchange事件，改变短信展示内容
    function changeMessageDemo() {
        var message_name = insSelect3.getText();
        var message_reason = $("#reason").val();
        var message_type = $("#walfareType").val();
        var message_typeValue = '';
        switch (message_type) {
            case '2':
                message_typeValue = '奖励';
                break;
            default:
                message_typeValue = '福利';
                break;
        }
        var message_url = $("#select3").val();
        var text = "【鑫泰科技】 您获得" + message_name + " 因[" + message_reason + "]送出的[" + message_typeValue + "]XX积分，款已付。请登录http://i.dorabox.com.cn/" + message_url + " 免费领取";
        $("#messageDemo >p").text(text);
    }

    //上一步下一步
    function nextStep(step) {
        sendrecord.insId = $("#select3").val();
        sendrecord.reason = $("#reason").val();
        sendrecord.walfareType = $("#walfareType").val();
        sendrecord.departmentId = $("#inputdepartment_import").val();

        switch (step) {

            //选择机构
            case 1:
                $("#step1").show();
                $("#step2").hide();
                break;

            //下载excel
            case 2:
                if ($("#select3").val() == 0) {
                    $("#alert3").css("display", "block");
                }
                else if ($("#inputdepartment_import").val() == '' && department != '') {
                    $("#alert4").css("display", "block");
                }
                else if ($("#reason").val() == '') {
                    $("#alert1").css("display", "block");
                }
                else {
                    $("#step2").show();
                    $("#step1").hide();
                    $("#step3").hide();
                }
                break;


            //上传excel
            case 3:
                $("#step3").show();
                $("#step2").hide();
                $('#upload_image_submit_form').attr('action', "import-integral-list?institutionCode=" + sendrecord.insId + "&departmentId=" + sendrecord.departmentId);
                break;

            default:
                break;
        }
    }

    //上传excel处理
    function uploadClick() {
        if ($("#upload_image").val() != '') {
            $("#upload_image_submit_form").submit();
            loading.show();
            $("#upload_exec_target").unbind();
            $("#upload_exec_target").load(function () {
                try {
                    $("#importlist").contents().find("tbody").html("");
                    var result = eval('(' + ($("#upload_exec_target").contents().find("body").html()) + ')');
                    if (result.status == 0 && result.data.iCount > 0) {
                        text = "导入成功！导入发分用户：" + result.data.iCount + "人，积分合计：" + result.data.amount + "分。请点击【确认发放】给用户发放积分。";
                        var textlist = '';
                        $(".two-error").text(text);
                        userList = [];
                        var user = {};
                        var re = result.data.right_data;
                        $.each(re, function (i, item) {
                            /*user = {};
                             user.id = item.id;
                             user.code = item.usercode;
                             user.name = item.username;
                             user.phone = item.phone;
                             user.integral = item.integral;
                             userList[i] = user;*/
                            textcontent = "<tr><td>" + item.usercode + "</td><td>" + item.username + "</td><td>" + item.phone + "</td><td>" + item.integral + "</td></tr>";
                            textlist = textlist + textcontent;
                        });
                        /*userList.integral_sum = result.data.amount;
                         */
                        textlist = textlist + "</tr>";
                        userList = result.data.right_data;
                        $("#confirm").attr("disabled", false);
                        $("#importlist").css("display", "block");
                        $("#importlist").contents().find("tbody").prepend(textlist);
                        $("#preStep").attr("disabled", true);

                    }
                    else if (result.status == 2) {
                        var re = eval('(' + result.message + ')');
                        $(".two-error").text(re);
                    }
                    else if (result.status == 1 && result.data.iCount > 0) {
                        var re = eval('(' + result.message + ')');
                        text = "导入失败！手机号码：" + re[0]["phone"] + "，姓名：" + re[0]["username"] + "导入内容不正确：" + re[0]["error"] + "请修改后重新导入！";
                        $(".two-error").text(text);
                    }
                    else {
                        var re = "导入失败，请检查文件的正确性！请确保导入的总积分不为0！";
                        $(".two-error").text(re);
                    }

                } catch (err) {
                    var re = $("#upload_exec_target").contents().find("h2").html();
                    $(".two-error").text(re);
                }
                $("#upload_image").val('');
                loading.hide();

            });
        }
    }

    //确认发放积分
    function confirmWalfare() {
        loading.show();
        var data = {};
        data.institutionId = sendrecord.insId;
        data.reason = sendrecord.reason;
        data.walfareType = sendrecord.walfareType;
        data.userintegrals = userList;
        data.departmentId = sendrecord.departmentId;
        /*data.userintegrals = "";
         for (var i = 0; i < userList.length; i++) {
         data.userintegrals += userList[i].id + "," + userList[i].name + "," + userList[i].integral + ";";
         }*/
        $("#confirm").attr("disabled", true);
        requestJson("save-integral-send-record-handler", data, true, function (re) {
            if (re.status == '0') {
                alert("发放成功!");
                refresh();
            } else {
                alert("发放失败！");
            }

        });
    }

    //搜索
    function search() {
        var institutionCode = $("#select2").val();
        if (institutionCode == 0) {
            alert("请选择机构！")
        } else {
            //   var createDate = $("#select1").val();
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            var filter;
            var f = $('#search1').val()._trim();
            var department = $("#inputdepartment").val();
            var href = window.location.href;
            var index = href.indexOf("?");
            if (index > 0) {
                href = href.substr(0, index);
            }
            href = setUrlParam(href, 'institutionCode', institutionCode);
            if (f != '') {
                href = setUrlParam(href, 'filter', f);
            }
            if (startTime != '') {

                href = setUrlParam(href, 'startTime', startTime);
            }
            if (endTime != '') {
                href = setUrlParam(href, 'endTime', endTime);
            }
            if (department != '') {
                href = setUrlParam(href, 'departmentId', department);
            }

            window.location.href = href;
            loading.show();
        }
    }

    //刷新页面
    function refresh() {
        location.reload();
        loading.show();
    }

    //清空时间选择
    function dataselect() {
        $("#select1").val("");
    }
</script>

<div class="panel panel-default">
    <div class="panel-body">
        <div class="row container-fluid">
            <div class="col-lg-1">
                <button class="btn btn-primary " type="button" onclick="addWalfare(0)">
                    <i class="fa fa-plus"></i> 发积分
                </button>
            </div>
            <div class="pull-left col-lg-3">
                <div id="select2"></div>
                <div id="department_div" style="display: none">
                    <div id="inputdepartment"></div>
                </div>
            </div>

            <div class="form-group col-lg-4">
                <div class="input-group input-large custom-date-range" data-date-format="yyyy-mm-dd">
                    <input type="text" class="form-control dpd1" id="startTime" name="from" placeholder="开始时间">
                    <span class="input-group-addon">To</span>
                    <input type="text" class="form-control dpd2" id="endTime" name="to" placeholder="结束时间">
                </div>
            </div>
            <div class="form-group col-lg-4">
                <div class="input-group">
                    <input type="text" class="form-control" id="search1" placeholder="请输入发分事由"
                           onkeypress="if(event.keyCode==13) {search();return false;}">
                        <span class="input-group-btn">
                            <button type="submit" class="btn btn-primary" onclick="search()"><i
                                    class="fa fa-search"></i> 搜索
                            </button>
                        </span>
                </div>
            </div>

        </div>
    </div>
</div>
<div class="panel panel-default">
    <div class="panel-body">
        <label class="col-sm-2 control-label">当前时间范围发放积分合计：</label>
        <label class="col-sm-3 control-label" id="totalIntegral"><?= $totalIntegral ?></label>
    </div>
</div>

<div class="panel">
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover table-condensed"
                   id="institutionTable">
                <thead>
                <tr>
                    <th>发分事由</th>
                    <th>创建时间</th>
                    <th>所属机构</th>
                    <th>发放数量</th>
                    <th>操作人</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <?php
                for ($i = 0; $i < count($record); $i++) {
                    ?>
                    <tr>
                        <td><?= $record[$i]['walfare_name'] ?></td>
                        <td><?= $record[$i]['create_time'] ?></td>
                        <td><?= $record[$i]['name'] . '  ' . $record[$i]['department_name'] ?></td>
                        <td><?= $record[$i]['integral'] . $record[$i]['integral_unit'] ?></td>
                        <td><?= $record[$i]['create_user_name'] ?></td>
                        <td>
                            <div class="btn-group">
                                <a class="btn btn-link" data-toggle="modal" data-walfare-id="<?= $record[$i]['id'] ?>"
                                   href="#detailWalfare">详情</a>
                            </div>
                            <!--<button class="btn btn-link btn-xs" type="button"
                                    onclick="walfareDetail('<?/*= $record[$i]['id'] */ ?>')">
                                详情
                            </button>-->

                        </td>
                    </tr>
                    <?php
                }
                ?>
                </tbody>
            </table>
        </div>
        <div class="pull-left">
            <?= \app\widgets\LinkPagerExt::widget(['pagination' => $pagination]) ?>
        </div>
    </div>
</div>

<!-- 导入积分-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="addWalfare" class="modal fade">
    <div class="modal-dialog modal-lg" id="step1" style="display:none">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">确认机构</h4>
            </div>
            <div class="modal-body modal-min-height">
                <div class="form-horizontal adminex-form col-lg-6" style="float: left;">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">所属机构</label>
                        <div class="col-sm-10">
                            <div id="select3"></div>
                            <label id='alert3' style="display: none;"><span style="color: red">请选择一个机构</span></label>
                        </div>
                    </div>
                    <div class="form-group" id="subIns" style="display: none">
                        <label class="col-sm-2 control-label">子&nbsp;机&nbsp;构&nbsp;</label>
                        <div class="col-sm-10">
                            <div id="departmentImport_div">
                                <div id="inputdepartment_import"></div>
                            </div>
                            <label id='alert4' style="display: none;"><span style="color: red">请选择一个子机构(部门)</span></label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label"><span style="color: red">*</span>事&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;由</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="reason" placeholder=""
                                   onchange="changeMessageDemo()" onkeyup="changeMessageDemo()">
                            <label id='alert1' style="display: none;"><span style="color: red">发分事由不允许为空</span></label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">类&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型</label>
                        <div class="col-sm-10">
                            <select class="form-control m-bot15" id="walfareType" onchange="changeMessageDemo()">
                                <option value="1">福利</option>
                                <option value="2">奖励</option>
                            </select>
                        </div>
                    </div>

                </div>
                <div class="col-lg-4" style="float: right; border-left: 1px solid #CCCCCC;">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" style="width: 100%; text-align: center;">积分发放短信预览</label>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <div class="messageDemo" id="messageDemo">
                                <img src="<?= $web ?>/images/mobile.jpg">
                                <p>【鑫泰科技】 您获得朵拉商城 因[]送出的[福利]XX积分，款已付。请登录http://i.dorabox.com.cn 免费领取</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-primary" onclick="nextStep(2)">下一步</button>
            </div>
        </div>
    </div>
    <div class="modal-dialog modal-lg" id="step2" style="display:none">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">下载excel</h4>
            </div>
            <div class="modal-body">

                <div class="form-group col-lg-6" style="float: left;">
                    <a id="excel-download" href="<?= $web ?>/walfaredemo.xlsx">
                        <img src="<?= $web ?>/images/hair-two-1.png">【点我】下载excel模板
                    </a>
                </div>
                <div class="col-lg-4" style="float: right; border-left: 1px solid #CCCCCC;">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" style="width: 100%; text-align: center;">积分发放短信预览</label>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <div class="messageDemo" id="messageDemo">
                                <img src="<?= $web ?>/images/mobile.jpg">
                                <p>【鑫泰科技】 您获得朵拉商城 因[]送出的[福利]XX积分，款已付。请登录http://i.dorabox.com.cn 免费领取</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-default" onclick="nextStep(1)">上一步</button>
                <button class="btn btn-primary" onclick="nextStep(3)">下一步</button>
            </div>
        </div>
    </div>
    <div class="modal-dialog modal-lg" id="step3" style="display:none">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">上传excel</h4>
            </div>
            <div class="modal-body">
                <div class="col-lg-6" style="float: left;">
                    <div class="form-group">
                        <div class="two-center">
                            <div class="two-words two-error-none">请点击【选择文件】导入EXCEL!<span
                                    style="color: red">注意：每次导入记录数不能超过5000条！</span>导入的时间可能很长，请耐心等待！
                            </div>
                            <div class="two-error" style="color: red"></div>
                        </div>
                    </div>
                    <div class="form-group">
                        <form id="upload_image_submit_form" enctype="multipart/form-data" method="post"
                              action="import-integral-list" target="upload_exec_target">
                            <input id="upload_image" name="file" type="file" onchange="uploadClick()"/>
                            <input type="hidden" name="dir" value="<?= $uploadDir ?>"/>
                            <img src="<?= $web ?>/images/hair-two-1.png">
                        </form>
                        <iframe id="upload_exec_target" name="upload_exec_target" style="display: none"></iframe>
                    </div>
                    <div class="form-group table-responsive" id="importlist" style="display: none">
                        <table class="table table-bordered table-hover table-condensed">
                            <thead>
                            <tr>
                                <th>用户编码</th>
                                <th>用户名</th>
                                <th>电话</th>
                                <th>分数</th>
                            </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="col-lg-4" style="float: right; border-left: 1px solid #CCCCCC;">
                    <div class="form-group">
                        <label class="col-sm-2 control-label" style="width: 100%; text-align: center;">积分发放短信预览</label>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <div class="messageDemo" id="messageDemo">
                                <img src="<?= $web ?>/images/mobile.jpg">
                                <p>【鑫泰科技】 您获得朵拉商城 因[]送出的[福利]XX积分，款已付。请登录http://i.dorabox.com.cn 免费领取</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-default" onclick="nextStep(2)" id="preStep">上一步</button>
                <button class="btn btn-primary" id="confirm" disabled="true" onclick="confirmWalfare()">确认发放</button>
            </div>
        </div>
    </div>
</div>

<!-- 提示框 -->
<div aria-hidden="true" role="dialog" tabindex="-1" id="institutionModal3" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">消息</h4>
            </div>
            <div class="modal-body" id="message">

                操作失败！

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="refresh()"> Ok</button>
            </div>
        </div>
    </div>
</div>

<!--积分详情-->
<div aria-hidden="true" role="dialog" tabindex="-1" id="detailWalfare" class="modal fade">
    <div class="modal-dialog modal-full">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
                <h4 class="modal-title">积分详情</h4>
            </div>
            <div class="modal-body" id="detail_content">
                正在加载数据....
            </div>
        </div>
    </div>
</div>